import uuid
import datetime
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.views import View
from utils.image_code import check_code
from web import models
from web.forms.account import RegisterModelForm, SendSmsForm, LoginSmsForm, LoginForm


def sms(request):
    """专门发短信的接口"""
    """
    发验证码短信接口
    url?mobile_phone=xxx&tpl=register    ---->注册模板id：571781
    """
    # 手机号和短信模板去form中校验
    form = SendSmsForm(request,data=request.GET)
    if form.is_valid():
        # 已经在SendSmsForm类中去校验通过，说明短信已经发送成功了
        # 因为在form中完成了短信发送以及redis存验证码(60s过期)
        return JsonResponse({'status':True})
    return JsonResponse({'status':False,'error':form.errors})


class RegisterView(View):
    """注册"""
    def get(self,request):
        """注册页面显示接口"""
        form = RegisterModelForm()
        return render(request,"register.html",{'form':form})

    def post(self,request):
        """注册接口"""
        data = request.POST
        form = RegisterModelForm(data)
        if form.is_valid():
            # 验证通过，写入数据库
            # save很牛逼，除了写入到数据库，还会自动剔除数据库没有的字段比如重复密码和验证码
            # 它会返回一个instance，就是存储进库的用户对象user
            instance = form.save()

            """
            # 方式一,免费用户还是存一份到用户交易表中
            policy_obj = models.PricePolicy.objects.filter(category=1,title="个人免费版").first()
            models.Transaction.objects.create(
                status=2,
                order=str(uuid.uuid4()),
                user=instance,
                # 价格策略
                price_policy=policy_obj,
                count=0,
                price=0,
                start_datetime=datetime.datetime.now()
            )
            """

            """
            方式二，默认是个人免费版,不在交易表中存免费用户的交易记录只存付费的
            所以我们这儿注册进来，啥也不管 用这个方式二   pass
            """
            pass
            return JsonResponse({'status':True,'data':'/login'})
        return JsonResponse({'status':False,'error':form.errors})


class LoginSmsView(View):
    """验证码登录方式"""
    def get(self,request):
        form = LoginSmsForm()
        return render(request, 'login_sms.html', {'form':form})

    def post(self,request):
        form = LoginSmsForm(request.POST)
        if form.is_valid():
            mobile_phone = form.cleaned_data.get('mobile_phone')
            # 登陆成功,利用手机号找到user对象
            user = models.UserInfo.objects.filter(mobile_phone=mobile_phone).first()
            # 请你把用户id和用户名存入session中待使用
            request.session['user_id'] = user.id
            request.session['username'] = user.username

            return JsonResponse({'status':True,'data':'/index'})
        return JsonResponse({'status':False,'error':form.errors})


class LoginView(View):
    """用户名密码登录"""
    def get(self,request):
        form = LoginForm(request)
        return render(request,'login.html',{'form':form})

    def post(self,request):
        form = LoginForm(request,request.POST)
        if form.is_valid():
            ##################密码校验在password钩子里(包括塞session)
            return JsonResponse({'status':True,'data':'/index'})
        return JsonResponse({'status':False,'error':form.errors})


def image_code(request):
    """生成图片验证码"""
    from io import BytesIO
    image_object,code = check_code()
    # 写进session中
    request.session['image_code'] = code
    request.session.set_expiry(60) # 60s过期

    stream = BytesIO()
    image_object.save(stream,'png')
    # 返回图片内容
    return HttpResponse(stream.getvalue())